package com.jiazhong.mingxing.boot.boot06.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.mingxing.boot.boot06.bean.Student;
import com.jiazhong.mingxing.boot.boot06.mapper.StudentMapper;
import com.jiazhong.mingxing.boot.boot06.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@CacheConfig(cacheNames = "findStudentById")
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    // 组成了redis中的key   findStudentById+动态的id
    @Cacheable(key = "#id")
    public Student findStudentById(String id) {
        log.info("开始查询{}的数据", id);
        return getById(id);
    }

    @Cacheable(cacheNames = "findAllStudent",key = "0")
    public List<Student> findAllStudent() {
        return list();
    }

    // 清除掉指定名称和参数的缓存信息
    @Caching(evict = {
            @CacheEvict(key = "#id"),
            @CacheEvict(cacheNames = "findAllStudent",key = "0")
    })
    public int removeStudentById(String id) {
        boolean b = removeById(id);
        return b ? 1 : 0;
    }

    @CachePut(key = "#student.id")
    public Student updateStudent(Student student) {
        // 1. 修改学生信息
        boolean b = updateById(student);
        if (b) {
            // 2. 重新查询学生信息
            return getById(student.getId());
        }
        // 3. 返回null
        return null;
    }
}
